package com.mdd.common.util.weifengqi.authorize;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mdd.common.entity.yangyangLeadingEnterprise.TAppReport;
import com.mdd.common.mapper.yangyangLeadingEnterprise.TAppReportMapper;
import com.mdd.common.util.HttpUtils;
import com.mdd.common.util.ToolUtils;
import com.mdd.common.util.weifengqi.encryptionPassword.AESUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.math3.util.Pair;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 微风企H5授权工具类(获取报告授权)
 */
@Slf4j
public class AuthorizeReportUtil {

    //报告授权请求路径
    public static final String url = "https://www.enterpriseservice.cn/authorization/?channelCode=gu9dr";
    public static final String url20250519 = "https://www.wfq2020.com/authorization/?channelCode=ts5lf";
    //获取授权链接 请求地址
    public static final String authorize_url = "https://api.enterpriseservice.cn/mini-program-index-api/accounts/authorize_url_ids";
    //渠道身份
    public static final String webAuthorizeChannelCode="gu9dr";
    //微风企H5获取报告授权结果回调地址
    public static final String cburl="http://zhongduniot.com:8888/api/ws/authorizeCallback";
    //微风企报告完成通知回调地址
    public static final String cburlData="http://zhongduniot.com:8888/api/ws/indicatorProcessingCallback";
    //接口生成，控制链接有效期及授权次数
    public static final String url_id="";

    //取报告---渠道编码号
    public static final String interfaceCode = "a6343b19103946a28401e3329b2f6899HA2TO";
    //取报告---加密串
    public static final String secretKey = "231ntTEDmFPlYKAJdteqK5We22jbd7TT2WESPFHPA/h1lQFp4mkBp6QZvik8D8N3";

    public static final Map<Integer, String> map;
    static {
        HashMap<Integer, String> tempMap = new HashMap<>();
        //税务风险报告-通用版,
        tempMap.put(1, "tax_risk_check");
        //政府补贴报告(财政补贴报告)
        tempMap.put(2, "fiscal_subsidies_analysis");
        //供应商尽调报告
        tempMap.put(3, "jindiao_supplier_analysis");
        //经营参谋报告
        tempMap.put(4, "business_strategy_analysis");
        //财务风险报告-简版(税务风险报告-简版)
        tempMap.put(5, "tax_risk_check_simple");
        //投资尽调报告
        tempMap.put(6, "invest_jindiao_analysis");
        //税务风险报告-税优版
        tempMap.put(7, "tax_risk_check_professional");
        //贷前报告
        tempMap.put(8, "");
        map = Collections.unmodifiableMap(tempMap);
    }


    /**
     * 获取授权链接
     * @return
     */
    public static String authorizeUrl(List<String> list) {
        Map<String, String> map = new HashMap<>();
        map.put("interfaceCode", interfaceCode);
        map.put("secretKey", secretKey);
        map.put("remain_times", "10");
        /**
         * finance_service_analysis:融资服务报告,
         * tax_risk_check:税务风险报告-通用版,
         * tax_risk_check_simple:税务风险报告-简版,
         * tax_risk_check_professional:税务风险报告-税优版,
         * jindiao_company_analysis:企业尽调报告,
         * fiscal_subsidies_analysis:财政补贴报告,
         * jindiao_supplier_analysis:供应商尽调报告,
         * business_strategy_analysis:经营参谋报告,
         * business_justice_analysis:工商司法报告(暂无接口),
         * invest_jindiao_analysis:投资尽调报告,
         * panoramic_report_analysis:企业全景报告（暂无接口）
         */

//        List<String> list = Arrays.asList(
//                "finance_service_analysis",
//                "tax_risk_check",
//                "tax_risk_check_simple",
//                "tax_risk_check_professional",
//                "jindiao_company_analysis",
//                "business_strategy_analysis",
//                "business_justice_analysis",
//                "invest_jindiao_analysis",
//                "jindiao_supplier_analysis",
//                "fiscal_subsidies_analysis",
//                "panoramic_report_analysis");
        String arr = JSONArray.toJSONString(list);
        map.put("report_type", arr);
        String result = HttpUtils.sendPostRawJson(authorize_url, map);
//        String result = HttpUtils.sendPostByWfq(url_id, map, MediaType.APPLICATION_FORM_URLENCODED);
        System.out.println("获取授权链接---请求参数："+JSON.toJSONString(map));
        System.out.println("获取授权链接---接口返回结果为："+result);
        /**
         * 返回示例
         * {"code":200,"message":"请求成功","data":{"url_id":"0c12a29e345211f0956202420a6529bf","remain_times":10,"expire_time":1,"report_permission":["finance_service_analysis","finance_service","tax_risk_check","tax_risk_check_simple","tax_risk_check_professional","tax_risk","jindiao_company_analysis","jindiao_supplier_analysis","invest_jindiao_analysis","yunjindiao_system","fiscal_subsidies_analysis","fiscal_subsidies","business_strategy_analysis","business_strategy"],"expire_time_hour":null}}
         */
        if(result!=null && !result.isEmpty()){
            try {
                JSONObject jsonObject = JSON.parseObject(result);
                if(jsonObject.getInteger("code")==200){
                    String url_id = jsonObject.getJSONObject("data").getString("url_id");
                    System.out.println("url_id为："+url_id);
                    return url_id;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static Pair<Boolean, String> authorizeReport(JSONObject message,List<String> idList) {
        String url_id = authorizeUrl(idList);
        if(url_id==null || url_id.isEmpty()){
            log.warn("获取授权链接失败");
            return new Pair<>(false, "获取授权链接失败");
        }
        //接口生成，控制链接有效期及授权次数
//        String url_id=url;
        //message加密信息
        String messagePassword="";
        try {
            messagePassword = AESUtils.encryptForSys(message);
        } catch (UnsupportedEncodingException e) {
            log.warn("加密失败", e);
            throw new RuntimeException(e);
        }
        //组装参数
        StringBuffer buffer = new StringBuffer().append(url20250519)
                .append("&webAuthorizeChannelCode=").append(webAuthorizeChannelCode)
                .append("&cburl=").append(cburl)
                .append("&message=").append(messagePassword)
                .append("&url_id=").append(url_id);
        System.out.println("请求路劲地址为："+buffer.toString());
        String result = HttpUtils.sendGet(buffer.toString());
        return new Pair<>(true, buffer.toString());
    }

    /**
     * 拼接参数，发送请求
     * @param companyName
     */
    public static Pair<Boolean, String> createParam(String companyName,String orderNo,List<String> idList) {
        JSONObject message = new JSONObject();
        log.warn("本次订单号为："+orderNo);
        message.put("orderNo", orderNo);
//        typeWay为空：（taxpayerId、companyName）必填其一
//        typeWay为1：authenticationMsg对象值必填（cognizantMobile 、cognizantName）
//        typeWay为2：firms数组必填 内部对象必填其一（companyName or taxpayerId）
//        typeWay为3：firms数组必填 内部对象必填其一（companyName or taxpayerId）且
//        authenticationMsg对象值必填（cognizantMobile 、cognizantName）
//        message.put("typeWay", null);
        message.put("companyName", companyName);
        log.warn("本次订单号为："+orderNo);
        log.warn("本次公司名称为："+companyName);
        Pair<Boolean, String> pair = authorizeReport(message,idList);
        return pair;
    }

    public static void main(String[] args) {
        String orderNo = ToolUtils.randomString(36);
        createParam("北京共融联创科技有限公司",orderNo,Arrays.asList("finance_service_analysis","tax_risk_check"));
    }




}
